package org.liuping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.liuping.common.utlis.OauthRequest;
import org.liuping.entity.UserEntity;
import org.liuping.service.UserService;
import org.liuping.vo.GiteeUserDataVo;
import org.liuping.vo.UserRegistryVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/oauth")
public class OauthController {

    @Resource
    private UserService userService;
    /**
     * 申请授权
     * @param response
     * @throws IOException
     */
    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = OauthRequest.getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 授权成功后的请求
     * @param callback
     * @return
     */
    @RequestMapping("/callback")
    public String login(AuthCallback callback) {
        //获取gitee返回的数据
        AuthRequest authRequest = OauthRequest.getAuthRequest();
        AuthResponse authResponse = authRequest.login(callback);
        //将data中的数据提取出来
        Object responseData = authResponse.getData();
        //先转化为json
        String jsonString = JSONObject.toJSONString(responseData);
        GiteeUserDataVo giteeUserDataVo = JSON.parseObject(jsonString, GiteeUserDataVo.class);
        //构造注册用数据
        UserRegistryVo userRegistryVo = new UserRegistryVo();
        userRegistryVo.setEmail(giteeUserDataVo.getEmail());
        userRegistryVo.setUsername(giteeUserDataVo.getUsername());
        //第三方调用userService进行注册
        UserEntity userEntity = userService.giteeOauthRegistry(userRegistryVo);
        //第三方调用登录功能
        userService.giteeOauthLogin(userEntity);
        //成功后跳转user界面
        return "user";
    }

}
